﻿using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using CommonTools;
using shop.Model;
using CommonTools.Basic;

namespace shop.Bll.BasicInfo
{

	/// <summary> 销售客户 基础资料 </summary>
	public class JCustomerBll : BasicBllParent, IFastQueryBll<JCustomer>
	{

		/// <summary>
		/// 查询
		/// </summary>
		/// <param name="code">查询代码</param>
		/// <param name="isDetails">是否明细</param>
		/// <param name="msg">错误消息</param>
		/// <returns></returns>
		public override IEnumerable<object> Query(string code, bool isDetails, out string msg)
		{
			msg = null;

			var list = DB.FSql.Select<JCustomer>()
			   .Where(s => s.IsDetails == isDetails && s.Isdel == false);

			if (string.IsNullOrEmpty(code) == false)
			{
				list = list.Where(a => a.Code.StartsWith(code));
			}

			//分业务员权限
			if (isDetails )
			{
				if (UserBll.CheckRight(this.ModifyRight) == false)
				{
					//只能看业务员自己的客户
					var saler = UserBll.CurrentUser.Name;
					list = list.Where(a => string.IsNullOrEmpty(a.SalesRep) || a.SalesRep == saler);
				}
			}

			return list.ToList();      //排序

		}




		#region 分组: 增删改

		/// <summary> 添加分类 </summary>
		public override bool AddGroup(object obj, IUser user, out string msg)
		{
			msg = null;
			if (!(obj is JCustomer model))
			{
				msg = Model.CN.Msg_InformationCannotBeBlank; // "辅助资料为空";
				return false;
			}

			model.PreparedBy = user.Name;
			var newModel = DB.FSql.Insert(model).ExecuteInserted();
			model.ID = newModel[0].ID;

			DB.FSql.Insert(new CLogs()
			{
				Computer = user.ComputerInfo,
				DocId = model.ID.ToString(),
				DocAction = "添加分类",
				DocName = nameof(JCustomer),
				Note = $"代码:{model.Code},名称:{model.Name}",
			}).ExecuteInserted();

			return true;

   
		}

		/// <summary> 删除分类 </summary>
		public override bool DeleteGroup(object obj, IUser user, out string msg)
		{
			msg = null;
			if (!(obj is JCustomer model))
			{
				msg = Model.CN.Msg_InformationCannotBeBlank; // "辅助资料为空";
				return false;
			}

			if (DB.FSql.Select<JCustomer>().Any(a => a.ID != model.ID
											 && a.Code.StartsWith(model.Code)
											 && a.Isdel == false) == false)     //检查分类下是否由明细
			{

				model.Isdel = true;
				DB.FSql.Update<JCustomer>()
					.Where(a => a.Isdel == false && a.Code == model.Code)
					.Set(a => a.Isdel, true)
					.ExecuteAffrows();

				var item = DB.FSql.Select<JCustomer>().Where(a => a.Isdel == false && a.Code == model.Code).ToOne();


				//日志
				DB.FSql.Insert(new CLogs()
				{
					Computer = user.ComputerInfo,
					DocId = item.ID.ToString(),
					DocAction = "删除分类",
					DocName = nameof(JCustomer),
					Note = $"代码:{item.Code},名称:{item.Name}",
				}).ExecuteAffrows();


			}
			else
			{
				msg = CN.Msg_GroupHasItemsCannotDelete;  // "此分组下还有项目, 不能删除!";
			}
			return false;
		}


		/// <summary> 修改分组 </summary>
		public override bool UpdateGroup(object obj, IUser user, out string err)
		{
			err = "";
			if (!(obj is JCustomer model))
			{
				err = Model.CN.Msg_InformationCannotBeBlank; // "辅助资料为空";
				return false;
			}


			var item = DB.FSql.Select<JCustomer>().Where(a => a.Isdel == false && a.Code == model.Code).ToOne();
			DB.FSql.Update<JCustomer>()
				.Set(a => a.Name, model.Name)
				.Set(a => a.FullName, model.FullName)
				.Where(a => a.Isdel == false && a.Code == model.Code)
				.ExecuteAffrows();

			//日志
			DB.FSql.Insert(new CLogs()
			{
				Computer = user.ComputerInfo,
				DocId = item.ID.ToString(),
				DocAction = "修改分类",
				DocName = nameof(JCustomer),
				Note = $"代码:{item.Code},名称:{item.Name}",
			}).ExecuteAffrows();

			return true;

		}

		#endregion


		#region 明细: 增删改


		/// <summary> 填加分类 </summary>
		public override bool Insert(object obj, IUser user, out string msg)
		{
			msg = null;
			if (!(obj is JCustomer model))
			{
				msg = Model.CN.Msg_InformationCannotBeBlank; // "辅助资料为空";
				return false;
			}
			model.PreparedBy = user.Name;
			model.Isdel = false;
			model.IsDetails = true;

			
	//        if (string.IsNullOrEmpty(model.Code))
	//        {
				//msg = CN.Msg_CodeCannotBeBlank;   // "资料代码不能为空";
	//            return false;
	//        }
			if (string.IsNullOrEmpty(model.Name))
			{
				msg = CN.Msg_NameCannotBeBlank;   // "资料名称不能为空";
				return false;
			}
			//if (this.GetByCode(model.Code) != null)
			//{
			//    msg = CN.Msg_CodeCannotRepeat;    // "代码不能重复";
			//    return false;
			//}
			else if (string.IsNullOrEmpty(model.SalesRep) )
			{
				msg = "业务员不能为空!";
				return false;
			}

			//检查重复
			if (DB.FSql.Select<JCustomer>().Any(a=> a.Isdel == false && a.Name == model.Name))
			{
				msg = "已经有相同名称客户!";
				return false;
			}

			//获取最大代码
			var maxnum = DB.FSql.Select<JCustomer>()
				.Where(a => a.Isdel == false && a.IsDetails == true && a.Code.StartsWith("1."))
				.Max(a => a.Code);

			if (string.IsNullOrEmpty(maxnum))
			{
				maxnum = "1.001";
			}
			else
			{
				var arr = maxnum.Split('.');
				if (arr.Length>1)
				{
					var n = arr[1].IsNull(0);
					n++;

					maxnum = "1." + (n).ToString().PadLeft(3, '0');
				}
				else
				{
					msg = "系统错误";
					return false;
				}
			}


			model.Code = maxnum;
			model.Isdel = false;
			model.IsDetails = true;

			var newmodel = DB.FSql.Insert(model).ExecuteInserted();
			model.ID = newmodel.FirstOrDefault().ID;

			DB.FSql.Insert(new CLogs()
			{
				Computer = user.ComputerInfo,
				DocId = model.ID.ToString(),
				DocAction = "添加",
				DocName = nameof(JCustomer),
				Note = $"代码:{model.Code},名称:{model.Name}",
			}).ExecuteAffrows();


			return true;


		}


		/// <summary> 修改 </summary>
		public override bool Update(object obj, IUser user, out string msg)
		{
			msg = null;
			if (!(obj is JCustomer model))
			{
				msg = Model.CN.Msg_InformationCannotBeBlank; // "辅助资料为空";
				return false;
			}

			if (string.IsNullOrEmpty(model.SalesRep) == false && model.SalesRep != user.Name)
			{
				//需要检查权限 
				if (UserBll.CheckRight(this.ModifyRight) == false)
				{
					msg = "对不起, 不是您的客户, 没有权限修改!";
					return false;
				}
			}

			if (model.ID <= 0)
			{
				msg = CN.Msg_IdCannotRepeat;   // "资料ID不能为空";
				return false;
			}
			if (string.IsNullOrEmpty(model.Code))
			{
				msg = CN.Msg_CodeCannotBeBlank;   // "资料代码不能为空";
				return false;
			}
			if (string.IsNullOrEmpty(model.Name))
			{
				msg = CN.Msg_NameCannotBeBlank;   // "资料名称不能为空";
				return false;
			}
			else if (string.IsNullOrEmpty(model.SalesRep))
			{
				msg = "业务员不能为空!";
				return false;
			}

			if (DB.FSql.Select<JCustomer>().Any(a => a.Isdel == false && a.Name == model.Name && a.ID != model.ID))
			{
				msg = "已经有相同名称客户!";
				return false;
			}


			model.PreparedBy = user.Name;
			
			DB.FSql.Update<JCustomer>()
				.SetSource(model)
				.ExecuteAffrows();


			//日志
			DB.FSql.Insert(new CLogs()
			{
				Computer = user.ComputerInfo,
				DocId = model.ID.ToString(),
				DocAction = "修改",
				DocName = nameof(JCustomer),
				Note = $"代码:{model.Code},名称:{model.Name}",
			}).ExecuteAffrows();

			return true;

		}


		/// <summary> 删除 </summary>
		public override bool Delete(object obj, IUser user, out string msg)
		{
			msg = null;
			if (!(obj is JCustomer model))
			{
				msg = CN.Msg_SystemError;
				return false;
			}
			if (model.ID <= 0)
			{
				msg = CN.Msg_IdCannotRepeat;   // "资料ID不能为空";
				return false;
			}

			if (string.IsNullOrEmpty( model.SalesRep) == false && model.SalesRep != user.Name)
			{
				//需要检查权限 
				if (UserBll.CheckRight(this.ModifyRight) == false)
				{
					msg = "对不起, 不是您的客户, 没有权限修改!";
					return false;
				}
			}

			model.Isdel = true;
			DB.FSql.Update<JCustomer>()
				.SetSource(model)
				.Set(a => a.Isdel, true)
				.Set(a => a.Name, model.Name+"_delete")
				.Set(a => a.Code, model.Code+"_delete")
				.ExecuteAffrows();

			//日志
			DB.FSql.Insert(new CLogs()
			{
				Computer = user.ComputerInfo,
				DocId = model.ID.ToString(),
				DocAction = "删除",
				DocName = nameof(JCustomer),
				Note = $"代码:{model.Code},名称:{model.Name}",
			}).ExecuteAffrows();

			return true;
		}


		#endregion



		#region 实现IFastQueryBll 接口, 在FastBox中使用

		/// <summary> 在查询窗体,报表中显式的名称 </summary>
		public string Title => "销售客户";

		/// <summary> 本地存储的明细 </summary>
		/// <remarks>如果基础资每次都从数据库查询, 这个没用, 保持null</remarks>
		public List<JCustomer> Items => null;


		/// <summary> 是否每次从数据库查询 </summary>
		public bool QueryFromDataBase => true;

		
		/// <summary> 存储在快速查询窗体中,显示的属性,及属性的显示, 这个暂时不用,以后删除 </summary>
		public Dictionary<string, string> DisplayColumns => null;


		/// <summary> 显示的列, 静态 </summary>
		private static readonly string[] _columns = new string[] { nameof(JCustomer.Code), nameof(JCustomer.Name) };


		/// <summary> 存储在快速查询窗体中,显示的属性 </summary>
		public string[] Columns => _columns;


		/// <summary> 实体模型的代码属性名称 </summary>
		public string CodeField => nameof(JCustomer.Code);



		/// <summary> 代码中级别的分隔符 </summary>
		public override string Separator => ".";



		/// <summary> 查询树形图的所有节点 </summary>
		public override IEnumerable<IFastTree> QueryTreeList()
		{
			var rst = DB.FSql.Select<JCustomer>().Where(a => a.IsDetails == false && a.Isdel == false);

			return rst.ToList();
		}


		/// <summary> 查询方法 </summary>
		public List<JCustomer> Query(string findText, string prefixCode = null)
		{
			var list = DB.FSql.Select<JCustomer>().Where(a => a.Isdel == false && a.IsDetails == true
										   && (a.Name.Contains(findText) || a.Code.Contains(findText)));

			if (string.IsNullOrEmpty(prefixCode) == false)
			{
				list = list.Where(a => a.Code.StartsWith(prefixCode));
			}

			return list.ToList().OrderBy(a => a.Code).ToList();
		}


		/// <summary> 查询树形图的一个节点下的所有内容 </summary>
		public List<JCustomer> QueryByGroup(string group)
		{
			return DB.FSql.Select<JCustomer>()
				.Where(w => w.IsDetails == true && w.Isdel == false && w.Code.StartsWith(group))
				.ToList().OrderBy(a => a.Code).ToList();        //排序
		}


		#endregion


		#region 权限

		/// <summary> 查询导出权限 </summary>
		public override string LookRight => "01.09.1";

		/// <summary> 保存权限 </summary>
		public override string SaveRight => "01.09.2";

		/// <summary> 修改别人单据权限 </summary>
		public string ModifyRight => "01.09.3";

		/// <summary> 删除别人单据权限 </summary>
		public string DeleteRight => "01.09.4";

		/// <summary> 审核,反审核权限 </summary>
		public override string CheckRight => "01.09.5";
		 


		#endregion



		#region 其他


		/// <summary> 使用代码查询一个 </summary>
		public JCustomer GetByCode(string code)
		{
			return DB.FSql.Select<JCustomer>()
			   .Where(w => w.IsDetails == true && w.Isdel == false && w.Code == code).ToOne();
		}
		/// <summary> 使用代码查询一个 </summary>
		public JCustomer GetByName(string name)
		{
			return DB.FSql.Select<JCustomer>()
			   .Where(w => w.IsDetails == true && w.Isdel == false && w.Name == name).ToOne();
		}

		#endregion



		#region 按钮,事件




		#endregion


		public override bool Check(object obj, IUser user, out string err)
		{
			throw new NotImplementedException();
		}

		public override bool UnCheck(object obj, IUser user, out string err)
		{
			throw new NotImplementedException();
		}




	}
}



 
